import React, {useState} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import {Button, Form, Input, message, Space, Upload, UploadProps} from 'antd';

type MyUploadProps = {
  value?: string;
  onSuccess: (url: string) => void;
}

const MyUpload:React.FC<MyUploadProps>=({onSuccess,value})=>{
  const [url,setUrl] = useState<string>(value || '');
  const props: UploadProps = {
    name: 'file',
    showUploadList:false,
    action: 'http://localhost:9902/api/admin/file/upload',
    withCredentials: true,
    data:{
      token:localStorage.getItem("token") || '',
    },
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        setUrl(info.file.response.data);
        onSuccess(info.file.response.data);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`).then();
      }
    },
  };

  return (
    <Space.Compact style={{width:'100%'}}>
      <Form.Item noStyle>
        <Input value={url} onChange={(e)=>{
          onSuccess(e.target.value);
          setUrl(e.target.value);
        }} />
      </Form.Item>
      <Form.Item noStyle>
        <Upload {...props}>
          <Button type='primary' icon={<UploadOutlined/>}>选择文件</Button>
        </Upload>
      </Form.Item>
    </Space.Compact>
  )
}

export default MyUpload;
